package argo.hot100.linklist;

public class AddTwoNumbers {


    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }

        ListNode p = l1, l = null, p1 = new ListNode(-1);
        int ncur = 0, cur = 0;
        while (l1 != null || l2 != null) {

            int n1 = l1 == null ? 0 : l1.val;
            int n2 = l2 == null ? 0 : l2.val;
            int bitsum = n1 + n2 + ncur;
            cur = bitsum % 10;
            ncur = bitsum / 10;

            l = l1 != null ? l1 : l2;
            p1.next = l;
            l.val = cur;
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
            p1 = l;

        }

        if (ncur > 0) {
            ListNode node = new ListNode(1);
            p1.next = node;
            p1 = node;
        }

        p1.next = null;

        return p;

    }

}
